package cat.joronya.supermanager.team;

import java.text.NumberFormat;
import java.util.Hashtable;
import java.util.Locale;

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.utils.ImageDownloader;

public class MyTeamDetailActivity extends ListActivity 
{
	// pel Log
	@SuppressWarnings("unused")
	private static final String TAG = "supermanager";
	private static final String URL_PHOTO_PLAYER = 
		"http://www.acb.com/fotos_cara/jugadores/J%sLACB55.jpg";
	
	private NumberFormat decform = null;
    private NumberFormat intform = null;
	
	private long id;
	private int day;
	private Cursor cursor = null;
	private Team team;
	
	private final ImageDownloader imageDownloader = new ImageDownloader(this, Supermanager.PLAYERS);
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.my_team);
        
       	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
       	decform.setMinimumFractionDigits(2);
       	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
       	intform.setGroupingUsed(true);
		
		// guardem id equip i jornada
        id = getIntent().getLongExtra("cat.joronya.supermanager.myteams.id",0);
        day = getIntent().getIntExtra("cat.joronya.supermanager.myteams.day",1);
        
        // retrieve team data
        team = getTeam(id, day);
        
        TextView name = (TextView) findViewById(R.id.my_team_name);
        name.setText(team.getName());
        TextView cash = (TextView) findViewById(R.id.my_team_cash);
        cash.setText(intform.format(team.getCash())+"€");
        // TODO: reactivar quan haguem parsejat el valor
        //TextView earnings = (TextView) findViewById(R.id.my_team_earnings2);
        //earnings.setText(intform.format(team.getEarnings())+"€");
        
		MyTeamDetailProvider provider = new MyTeamDetailProvider();
		Hashtable<String, Float> totals = provider.getTotals(getApplicationContext(), team.getIdEqu(), day);
        
        TextView cost = (TextView) findViewById(R.id.my_team_cost2);
        cost.setText(intform.format(totals.get("COST"))+"€");
        TextView totalPunts = (TextView) findViewById(R.id.my_team_rating2);
        totalPunts.setText(decform.format(totals.get("RATING")));
        
        // tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		cursor = provider.getTeam(getApplicationContext(), team.getIdEqu(), day);
		
		startManagingCursor(cursor);
		
		// Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.my_team_row,
        		cursor,
                new String[] { Supermanager.MyTeamDetail.ID_PLAYER,
        					   Supermanager.Market.STATUS,
        					   Supermanager.Market.NACIONALITY,
        					   Supermanager.Market.NAME,
        					   Supermanager.MyTeamDetail.WIN,
        					   Supermanager.Market.TEAM,
        					   Supermanager.Market.BALANCE,
        					   Supermanager.MyTeamDetail.PRICE,
        					   Supermanager.MyTeamDetail.RATING,
        					   Supermanager.MyTeamDetail.SIGNING_DAY,
        					   Supermanager.MyTeamDetail.COST,
        					   Supermanager.MyTeamDetail.RATING_AVERAGE
        					   }, 
        		new int[] { R.id.avatar,
							R.id.stick,
							R.id.stick,
							R.id.player_name,
        					R.id.player_victory,
        					R.id.player_team,
        					R.id.player_balance,
        					R.id.player_price,
        					R.id.player_rating,
        					R.id.player_buy_day,
        					R.id.player_buy_price,
        					R.id.player_average
        					});
        
        adapter.setViewBinder(new ViewBinder()
        {
        	// format data
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		// ID_PLAYER
        		if( aColumnIndex == 1 )
        		{
        			String cod = aCursor.getString(aColumnIndex);
        			imageDownloader.download(String.format(URL_PHOTO_PLAYER, cod), (ImageView) aView);
        			return true;
        		}
        		// STATUS
        		else if( aColumnIndex == 7 )
        		{
        			// si te status, cal ficar stick corresponent
        			String status = aCursor.getString(aColumnIndex);
        			if( "lesio.png".equals(status) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.lesio);
        				statusView.bringToFront();
        			}
        			else if( "semafor.png".equals(status) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				// TODO: guardar drawable de semafor
        				statusView.setImageResource(R.drawable.lesio);        				
        				statusView.bringToFront();
        			}
        			else
        			{
        				aView.setVisibility(View.INVISIBLE);
        			}
        			return true;
        		}
        		// NACIONALITY
        		else if( aColumnIndex == 6 )
        		{
        			// si te nacionality, cal ficar stick corresponent
        			String nacionality = aCursor.getString(aColumnIndex);
        			if( "nacional.png".equals(nacionality) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.nacional);
        				statusView.bringToFront();
        			}
        			else if( "extra.png".equals(nacionality) )
        			{
        				aView.setVisibility(View.VISIBLE);
        				ImageView statusView = (ImageView)aView;
        				statusView.setImageResource(R.drawable.extra);        				
        				statusView.bringToFront();
        			}
        			else
        			{
        				aView.setVisibility(View.INVISIBLE);
        			}
        			return true;
        		}
        		// VICTORY
        		else if( aColumnIndex == 2 )
        		{
        			int victory = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(victory==1?"(+)":"");
        			return true;
        		}
        		// RATING
        		else if( aColumnIndex == 10 )
        		{
        			float average = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(decform.format(average));
        			return true;
        		}
        		// AVERAGE
        		else if( aColumnIndex == 13 )
        		{
        			float average = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(decform.format(average));
        			return true;
        		}
        		// PRICE
        		else if( aColumnIndex == 9 )
        		{
        			int price = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(intform.format(price)+"€");
        			return true;
        		}
        		// PRICE BUY
        		else if( aColumnIndex == 12 )
        		{
        			int price = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(intform.format(price)+"€");
        			return true;
        		}
        		// DAY
        		else if( aColumnIndex == 11 )
        		{
        			int price = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText("(jª"+price+")");
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        });

        setListAdapter(adapter);
	}
	
	private Team getTeam(long id, int day)
	{
		Uri teamUri = Uri.withAppendedPath(Supermanager.MyTeam.CONTENT_URI, ""+id);
		Cursor c = getContentResolver().query(teamUri, Supermanager.MyTeam.PROJECTION, 
				Supermanager.MyTeam.DAY+"=?",
				new String[]{
					""+day
				},
				null);
		
		if( c.moveToFirst() )
		{
			Team team = new Team();
			team.setIdEqu(c.getString(1));
			team.setName(c.getString(2));
			team.setDay(c.getInt(3));
			int cash = c.getInt(14);
			team.setCash(cash);
			int earnings = c.getInt(15);
			team.setEarnings(earnings);
			return team;
		}
		
		return null;
	}
}
